package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author 衷岚
 * @version 1.0
 */
public class SimpleRedisLock implements ILock {

    private static final String KEY_PREFIX = "lock:";
    private String value = UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        //配置脚本位置
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        //配置返回值
        UNLOCK_SCRIPT.setResultType(Long.class);
    }


    private String name;//userId
    private RedisTemplate redisTemplate;



    public SimpleRedisLock(String name,RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }


    @Override
    public boolean tryLock(long time) {
        //获取当前线程
        long threadId = Thread.currentThread().getId();
        //获取锁
        Boolean success = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, value + threadId, time, TimeUnit.SECONDS);
        return success == null ? false : success;
    }

    @Override
    public void unlock() {
        //执行lua脚本
        redisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                value + Thread.currentThread().getId());
    }

    /**
     * 释放锁
     */



//    @Override
//    public void unlock() {
//        //判断锁的值前后是否一致
//
//        //redis中锁的值
//        String cacheValue = (String) redisTemplate.opsForValue().get(KEY_PREFIX + name);
//
//        long threadId = Thread.currentThread().getId();
//        //当前线程锁的值
//        value = value + threadId;
//
//        //一致  释放锁
//        if (value.equals(cacheValue)){
//            redisTemplate.delete(KEY_PREFIX + name);
//        }
//        //不一致 不释放
//
//
//    }
}
